package com.zzzy.doc.service.mydoc;

import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.CglibBeanCopierUtil;
import com.zzzy.doc.common.enums.DocStatusEnum;
import com.zzzy.doc.dao.entity.Document;
import com.zzzy.doc.vo.document.my.DocAddReq;
import com.zzzy.framework.common.util.SecurityUtils;
import com.zzzy.framework.dto.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class MyDocDraftService extends MyDocService {

    @Transactional
    public Long addDoc(DocAddReq addReq) {
        Long docId = doAddDoc(addReq);
        docAdviceService.addAdvice(docId);
        return docId;
    }

    private Long doAddDoc(DocAddReq addReq) {
        Document document = CglibBeanCopierUtil.copy(addReq, Document.class);
        LocalDateTime dateNow = LocalDateTime.now();
        document.setCreateTime(dateNow);
        document.setUpdateTime(dateNow);
        document.setStatus(DocStatusEnum.DRAFT.getValue());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        document.setUserId(loginUser.getId());
        document.setUserName(loginUser.getNickName());
        document.setOperatorId(loginUser.getId());
        document.setOperatorName(loginUser.getNickName());
        baseMapper.insert(document);
        docFileService.addDocFileByTemplateId(document.getId(), addReq.getTemplateId());
        return document.getId();
    }

    @Transactional
    public void draftComplete(Long id) {
        Document document = getDocByIdForUpdate(id);
        docAdviceService.addAdvice(id, "拟稿完毕进入审核修订阶段");

        AssertUtil.isEquals(DocStatusEnum.DRAFT.getValue(), document.getStatus(), "公文状态错误");
        document.setStatus(DocStatusEnum.AUDIT.getValue());
        document.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(document);
    }

}
